const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 获取分类列表
router.get('/', async (req, res) => {
  try {
    const { parent_id } = req.query;
    let query = `
      SELECT c.*, 
             (SELECT COUNT(*) FROM products WHERE category_id = c.id) as product_count
      FROM product_categories c
    `;

    const params = [];
    if (parent_id) {
      query += ' WHERE parent_id = ?';
      params.push(parent_id);
    } else {
      query += ' WHERE parent_id IS NULL';
    }

    query += ' ORDER BY c.created_at DESC';

    const [categories] = await db.query(query, params);

    // 如果不是查询子分类，则获取每个分类的子分类
    if (!parent_id) {
      for (let category of categories) {
        const [subCategories] = await db.query(`
          SELECT c.*, 
                 (SELECT COUNT(*) FROM products WHERE category_id = c.id) as product_count
          FROM product_categories c
          WHERE parent_id = ?
          ORDER BY c.created_at DESC
        `, [category.id]);
        category.sub_categories = subCategories;
      }
    }

    res.json({
      success: true,
      data: categories
    });
  } catch (error) {
    console.error('获取分类列表错误:', error);
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

// 获取分类详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const [categories] = await db.promise().query(`
      SELECT c.*, 
             (SELECT COUNT(*) FROM products WHERE category_id = c.id) as product_count
      FROM product_categories c
      WHERE c.id = ?
    `, [id]);

    if (categories.length === 0) {
      return res.status(404).json({
        success: false,
        error: '分类不存在',
        code: 404
      });
    }

    res.json({
      success: true,
      data: categories[0]
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

// 获取分类下的商品
router.get('/:id/products', async (req, res) => {
  try {
    const { id } = req.params;
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;

    // 获取总数
    const [countResult] = await db.promise().query(
      'SELECT COUNT(*) as total FROM products WHERE category_id = ?',
      [id]
    );
    const total = countResult[0].total;

    // 获取商品列表
    const [products] = await db.promise().query(`
      SELECT p.*
      FROM products p
      WHERE p.category_id = ?
      ORDER BY p.created_at DESC
      LIMIT ? OFFSET ?
    `, [id, limit, offset]);

    res.json({
      success: true,
      data: {
        items: products,
        pagination: {
          current_page: page,
          total_pages: Math.ceil(total / limit),
          total_items: total,
          per_page: limit
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

module.exports = router; 